<template>
  <layout class="member-list-table">
    <template slot="title">
      <div class="title-container">
        <span style="margin-right: 10px"><b>农户信息列表</b></span>
      </div>

      <!-- <a-button
        type="primary"
        icon="plus"
        @click="tableImportExecl({
          headers: 2,
          title: '农户数据待确认表'
        })"
        >导入</a-button
      > -->
    </template>

    <!-- 顶部操作 -->
    <section slot="search">
      <custom-form
        ref="search-form"
        class="search-form"
        :class="{ 'one-line': isOpen }"
        v-model="tableSearch"
        layout="inline"
        mode="search"
        :FormList="searchColumns"
      >
      </custom-form>

      <section style="margin-top: 4px" class="search-operate">
        <a-button
          type="default"
          :icon="isOpen ? 'down' : 'up'"
          @click="isOpen = !isOpen"
          >{{ isOpen ? '展开' : '折叠' }}搜索栏</a-button
        >
        <a-button
          class="action-button primary-button"
          type="primary"
          @click="search()"
        >
          <a-icon type="search" />搜索
        </a-button>

        <a-button
          type="primary"
          icon="plus"
          class="primary-button"
          style="margin-right: 10px"
          :auth="{
            keys: ['member.add', currentAreaId.length === 14],
            relate: 'and',
          }"
          @click="handlerTableAdd"
          >新增农户</a-button
        >
        <section class="opreate">
          <a-button-group>
            <a-button @click="handlerTableExportExecl()"
              >按搜索条件导出电子表（模板）</a-button
            >
            <a-button
              :disabled="currentAreaId.length < 9"
              @click="$refs.MemberImport.handlerUploadExecl()"
              >导入电子表更新数据</a-button
            >
             <a-button
              class="action-button"
              showDefaultLabel
              @click="handlerUploadProcess('member', '导入')"
            >
              查看上传进度
            </a-button>
          </a-button-group>
          <a-button
            :loading="tableLoading"
            class="action-button"
            @click="handlerBatchChangeStatus"
          >
            <span>批量修改当前行政区下补贴状态</span>
          </a-button>

          <a-button
            :loading="tableLoading"
            v-if="isThanArea"
            @click="handlerSiftDead"
          >
            <span>筛查死亡农户</span>
          </a-button>

          <a-button
            type="default"
            class="action-button"
            :auth="{
              keys: ['member.publish-add', !(currentAreaId.length < 12)],
              relate: 'and',
            }"
            @click="handlerPublic(false)"
            >起草公示信息</a-button
          >

          <a-button
            type="default"
            auth="member.export-fund-release"
            @click="handlerExportExecl(true)"
            >导出资金分户明细表</a-button
          >
        </div>
        </section>
      </section>

      <section class="field-select">
        <!-- <label for="">显示表头：</label>
        <a-radio-group v-model="renderFields">
          <a-radio-button :value="1" icon="bars"> 农户信息 </a-radio-button>
          <a-radio-button :value="2"> 基本面积 </a-radio-button>
          <a-radio-button :value="3"> 补贴信息 </a-radio-button>
          <a-radio-button :value="0" icon="bars"> 全部信息 </a-radio-button>
        </a-radio-group> -->
        <a-tabs v-model="renderFields" type="card">
          <a-tab-pane :key="1" tab="农户信息"></a-tab-pane>
          <a-tab-pane :key="2" tab="基本面积"></a-tab-pane>
          <a-tab-pane :key="3" tab="补贴信息"></a-tab-pane>
          <a-tab-pane :key="0" tab="全部信息"></a-tab-pane>
        </a-tabs>

        <div class="extends">
          <a-button
            type="link"
            :auth="{
              keys: ['member.publish-add', !(currentAreaId.length < 12)],
              relate: 'and',
            }"
            @click="handlerPublic(false)"
            >起草公示信息</a-button
          >

          <a-button
            type="link"
            auth="member.export-fund-release"
            @click="handlerExportExecl(true)"
            >导出资金分户明细表</a-button
          >
        </div>
      </section>

      <!-- <a-tabs v-model="renderFields" type="card">
        <a-tab-pane :key="1" tab="农户信息"></a-tab-pane>
        <a-tab-pane :key="2" tab="基本面积"></a-tab-pane>
        <a-tab-pane :key="3" tab="补贴信息"></a-tab-pane>
        <a-tab-pane :key="0" tab="全部信息"></a-tab-pane>
      </a-tabs> -->

      <!-- 查错数据 -->
      <!-- <custom-form
        ref="search-form"
        class="search-form"
        v-model="currentFilter"
        layout="inline"
        mode="filter"
        :FormList="searchColumns"
      >
        <a-button
          class="action-button"
          type="primary"
          @click="search()"
        >查错/查重</a-button>
      </custom-form> -->
    </section>

    <!-- 产品列表 -->
    <a-table
      :dataSource="tableData"
      :columns="tableColumns"
      :rowKey="(record) => record.iid"
      :row-selection="rowSelection"
      :pagination="false"
      :loading="tableLoading"
      @change="handleTableChange"
      class="table-total"
      :scroll="{
        x: '100%',
        y: tableClientHeight,
      }"
      :customRow="customTableRow"
      bordered
    >
      <template slot="member_addr" slot-scope="row">
        <a-tooltip>
          <template slot="title">
            {{ row.member_addr }}
          </template>
          <a-button type="link">{{
            row.member_addr && row.member_addr.length > 6
              ? '...' + row.member_addr.slice(row.member_addr.length - 6)
              : row.member_addr
          }}</a-button>
        </a-tooltip>
        <!-- {{row.member_addr}} -->
      </template>
      <template slot="member_sex" slot-scope="row">
        {{ getLabel(row.member_sex, [], 'member_sex') }}
      </template>
      <template slot="pay_unit" slot-scope="row">
        {{ getLabel(row.pay_unit, [], 'pay_unit') }}
      </template>

      <template slot="pay_unit_base" slot-scope="row">
        {{ getLabel(row.pay_unit_base, [], 'pay_unit_base') }}
      </template>

      <template slot="member_addr" slot-scope="row">
        <a-tooltip>
          <template slot="title">
            {{ row.member_addr }}
          </template>
          <a-button type="link">{{
            row.member_addr && row.member_addr.length > 6
              ? '...' + row.member_addr.slice(row.member_addr.length - 6)
              : row.member_addr
          }}</a-button>
        </a-tooltip>
        <!-- {{row.member_addr}} -->
      </template>

      <template slot="bt_size" slot-scope="row">
        {{ ((+row.pay_unit === 2 ? +row.field : +row.plant) || 0).toFixed(3) }}
      </template>

      <template slot="plant" slot-scope="row">
        {{ row.plant || 0 }}
      </template>

      <template slot="readme" slot-scope="row">
        <a-tooltip v-if="row.readme" placement="topLeft" :title="row.readme">
          {{
            row.readme.length > 5 ? '...' + row.readme.slice(-5) : row.readme
          }}
        </a-tooltip>
      </template>

      <template slot="pay_unit_base_title">
        基础面积依据
        <a
          class="ant-dropdown-link"
          @click="handlerUpdateSubsidy('unit_base')"
          v-if="isShowPayUnitSet"
        >
          [设置]
        </a>
      </template>

      <template slot="pay_price_title"> 补贴标准<br />(元/亩) </template>

      <template slot="pay_unit_title">
        补贴核算依据
        <a
          class="ant-dropdown-link"
          @click="handlerUpdateSubsidy('unit')"
          v-if="isShowPayUnitSet"
        >
          [设置]
        </a>
      </template>

      <template slot="bt_size_title"> 补贴面积<br />（亩） </template>

      <template slot="pay_price_total_title"> 补贴金额<br />（元） </template>
      <template slot="field1" slot-scope="row, record, index">
        <span v-if="index === 0">
          {{ row.field1 || 0 }}
        </span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click.stop="handlerManageFarmLand(row, 1)"
          >{{ row.field1 || 0 }}</a-button
        >
      </template>
      <template slot="field2" slot-scope="row, record, index">
        <span v-if="index === 0">
          {{ row.field2 || 0 }}
        </span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click.stop="handlerManageFarmLand(row, 2)"
          >{{ row.field2 || 0 }}</a-button
        >
      </template>
      <template slot="field3" slot-scope="row, record, index">
        <span v-if="index === 0">
          {{ row.field3 || 0 }}
        </span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click.stop="handlerManageFarmLand(row, 3)"
          >{{ row.field3 || 0 }}</a-button
        >
      </template>

      <template slot="field_confirm_t" slot-scope="row, record, index">
        <span v-if="true">
          {{ (+row.field_confirm_t || 0).toFixed(3) }}
        </span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click.stop="handlerAreaManage(row, 'field_confirm_t')"
          >{{ (+row.field_confirm_t || 0).toFixed(3) }}</a-button
        >
      </template>

      <template slot="field_confirm" slot-scope="row, record, index">
        <span v-if="true">
          {{ (+row.field_confirm || 0).toFixed(3) }}
        </span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click.stop="handlerAreaManage(row, 'field_confirm')"
          >{{ (+row.field_confirm || 0).toFixed(3) }}</a-button
        >
      </template>

      <template slot="field_tax" slot-scope="row, record, index">
        <span v-if="true">
          {{ (+row.field_tax || 0).toFixed(3) }}
        </span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click.stop="handlerAreaManage(row, 'field_tax')"
          >{{ (+row.field_tax || 0).toFixed(3) }}</a-button
        >
      </template>

      <template slot="plant" slot-scope="row, record, index">
        <span v-if="true">
          {{ (+row.plant || 0).toFixed(3) }}
        </span>
        <a-button
          v-else
          type="link"
          showDefaultLabel
          @click.stop="handlePlantEdit(row, 'grain')"
          >{{ (+row.plant || 0).toFixed(3) }}</a-button
        >
      </template>

      <!-- 按钮区 -->
      <template slot="action" slot-scope="row, record, index">
        <template v-if="index !== 0">
          <a-button
            class="action-button"
            type="link"
            size="small"
            auth="member.edit"
            @click.stop="handleTableEdit(row)"
            >编辑</a-button
          >
          <a-button
            class="action-button"
            type="link"
            size="small"
            auth="member.list"
            @click.stop="handlerFamily(row)"
            >管理家庭成员</a-button
          >
          <a-popconfirm
            title="您确认要删除该条数据?"
            ok-text="确认"
            cancel-text="取消"
            @confirm="tableDel(row)"
          >
            <a-button
              class="action-button"
              type="link"
              auth="member.delete"
              size="small"
              @click.stop
              >删除</a-button
            >
          </a-popconfirm>
          <!-- <a-button
            class="action-button"
            type="link"
            size="small"
            auth="member.field"
            @click.stop="handlerManageFarmLand(row, '')"
            >耕地信息</a-button
          >
          <a-button
            class="action-button"
            type="link"
            size="small"
            auth="member.plant"
            @click.stop="handlePlantEdit(row, 'grain')"
            >种粮信息</a-button
          > -->
        </template>
      </template>
    </a-table>

    <!-- 产品列表分页器 -->
    <a-pagination
      slot="paging"
      :pageSizeOptions="pageSizes"
      :total="total"
      :show-total="showTotal"
      showSizeChanger
      :pageSize="pageSize"
      v-model="currentPage"
      @showSizeChange="changePageSize"
      @change="changePage"
    >
    </a-pagination>

    <!-- 其他  -->
    <section slot="other">
      <!-- <a-checkbox></a-checkbox>
      <a-button-group>
        <a-button>全选当页</a-button>
        <a-button>全选取消</a-button>
        <a-button>反选当页</a-button>
      </a-button-group> -->
    </section>

    <!-- 编辑产品数据 -->
    <a-modal
      :visible="visible"
      :title="visibleTitle"
      centered
      :width="renderFields === 1 ? 500 : 1000"
      @cancel="visible = false"
      @ok="handleFormSubmit"
    >
      <div class="edit-container">
        <custom-form
          ref="custom-form"
          class="custom-form"
          v-model="currentRow"
          :FormList="formColumns"
          :mode="customMode"
          v-bind="formItemLayout"
          layout="horizontal"
        >
          <template slot="field" slot-scope="{ params }">
            <a-row>
              <a-row> 补贴面积/耕地面积/实际耕种面积（亩） </a-row>
              <!-- <a-alert
                message="耕地面积由下3个字段计算生成，不得小于0"
              ></a-alert> -->
              <a-row class="custom-field">
                <a-col span="5">
                  <span>基础面积</span>
                  <a-input
                    v-model="params.field1"
                    placeholder="输入承包地面积"
                  ></a-input>
                </a-col>
                <a-col span="1">+</a-col>
                <a-col span="5">
                  <span>增加面积</span>
                  <a-input
                    v-model="params.field2"
                    placeholder="输入增加面积"
                  ></a-input>
                </a-col>
                <a-col span="1">-</a-col>
                <a-col span="5">
                  <span>减少面积</span>
                  <a-input
                    v-model="params.field3"
                    placeholder="输入减少面积"
                  ></a-input>
                </a-col>
                <a-col span="1">=</a-col>
                <a-col span="5">
                  <span>补贴面积</span>
                  <a-input
                    :value="
                      Math.max(
                        (+params.field1 || 0) +
                          (+params.field2 || 0) -
                          (+params.field3 || 0),
                        0
                      ).toFixed(3)
                    "
                    disabled
                  ></a-input>
                </a-col>
              </a-row>
              <!-- <a-row class="field-count">
                <a-input
                  :value="
                    Math.max(
                      (+params.field1 || 0) + (+params.field2 || 0) - (+params.field3 || 0),
                      0
                    ).toFixed(3)
                  "
                  disabled
                ></a-input>
              </a-row> -->
            </a-row>
          </template>
        </custom-form>
        <!-- <custom-form
          v-if="formMode === 'edit'"
          ref="custom-form1"
          class="custom-form"
          v-model="currentRow"
          :FormList="formFieldColumns"
          :mode="customMode"
          v-bind="formItemLayout"
          layout="horizontal"
        >
          <template slot="field" slot-scope="{ params }">
            <a-row>
              <a-row>
                <a-input
                  :value="
                    Math.max(
                      +params.field1 + +params.field2 - +params.field3,
                      0
                    ).toFixed(3)
                  "
                  disabled
                ></a-input>
              </a-row>
              <a-alert
                message="耕地面积由下3个字段计算生成，不得小于0"
              ></a-alert>
              <a-row class="custom-field">
                <a-col span="7">
                  <span>承包地</span>
                  <a-input
                    v-model="params.field1"
                    placeholder="输入承包地面积"
                  ></a-input>
                </a-col>
                <a-col span="1">+</a-col>
                <a-col span="7">
                  <span>增加面积</span>
                  <a-input
                    v-model="params.field2"
                    placeholder="输入增加面积"
                  ></a-input>
                </a-col>
                <a-col span="1">-</a-col>
                <a-col span="7">
                  <span>减少面积</span>
                  <a-input
                    v-model="params.field3"
                    placeholder="输入减少面积"
                  ></a-input>
                </a-col>
              </a-row>
            </a-row>
          </template>
        </custom-form> -->
      </div>
    </a-modal>

    <!-- 管理耕地信息 -->
    <a-modal
      :title="currentRow.member_nam + '-当前确权耕地汇总表'"
      placement="right"
      width="80%"
      :visible="drawerVisible"
      :footer="null"
      :maskClosable="false"
      :bodyStyle="{ maxHeight: '80vh', minHeight: '60vh' }"
      @cancel="handlerFarmLandCancel"
    >
      <Farmland
        :currentField="currentRow"
        :currentFieldType="currentFieldType"
      />
    </a-modal>

    <MemberImport ref="MemberImport" :currentAreaId="currentAreaId" />
  </layout>
</template>

<script lang="ts">
import { Mixins, Component, Watch, Vue, Prop } from 'vue-property-decorator'
import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin, AppMixin, TableExtendImport } from '@/mixin'

import { TableLayout } from '@/layouts'
import CustomForm from '@/components/src/Form'
import { famerServices, IGrain, IMember } from '@/common/services/famer'
import { subsidyServices, IStatistics } from '@/common/services/subsidy'
import { memberRole, PayUnitType } from '@/common/enum'
import { RosterMixins } from './mixin'
import { PublishMixin } from './PublishMixin'
import { BatchChangeUsedStatusMixin } from './BatchChangeUsedStatusMixin'
import Farmland from '../grain/Farmland.vue'
import Family from '../list/Family.vue'
import MemberImport from './MemberImport.vue'
import UpdateSubsidy from './UpdateSubsidy.vue'
import AreaManage from './AreaManage.vue'
import { publicServices } from '@/common/services/public'
import { userModule } from '@/store/modules/user'
import Result from '../death/Result.vue'
import UploadProcess from '../../fund-release/list/UploadProcess.vue'

@Component({
  components: {
    Layout: TableLayout,
    CustomForm,
    Farmland,
    Family,
    MemberImport,
    UploadProcess
  },
})
export default class AdminList extends Mixins(
  EventsMixin,
  TableExtendImport,
  AuthMixin,
  AppMixin,
  PublishMixin,
  RosterMixins,
  BatchChangeUsedStatusMixin
) {
  @Prop({
    type: String,
  })
  public currentAreaName!: string

  public commonParams = {
    s_a_id: '',
  }

  public isOpen = true

  // 产品列表搜索条件
  public tableSearch = {
    // 户主
    role: '1',
    is_pub: '',
    is_used: '',
    switch: '2',
  }

  // 筛选条件
  public currentFilter = {
    member_filter: [],
  }

  public requireExportFields = ['family_id', 'member_nam', 's_a_id']

  // 自定义mode
  public customMode = 'add'
  public hasTotalRow = true

  public customRow = (record: IMember) => {
    // 判断是否有异常信息
    return {
      class: {
        'has-error': record.error_msg,
      },
      on: {
        click: () => {},
      },
    }
  }

  // 已选择补贴用户
  public isUsed = 0
  // 批量设置补贴用户状态
  // public batchIsUsed = false;

  // get batchIsUsed() {
  //   return Boolean(+this.isUsed) && (+this.isUsed === +this.total)
  // }
  public batchIsUsed = false
  public selectUsedStatus = ''
  public batchChangeUsedVisible = false

  // @Watch('batchIsUsed')
  public handlerChangeBatchIsUsed(val: boolean) {
    if (!this.selectUsedStatus) {
      this.$message.error('请选择批量操作的补贴状态！')
      return
    }
    this.batchIsUsedLoading = true
    subsidyServices
      .setSubsidyStatus({
        is_area: true,
        s_a_id: this.currentAreaId,
        is_used: this.selectUsedStatus, // val ? '1' : '2',
      })
      .then(() => {
        this.getData()
        this.$message.success('补贴状态更新成功')
      })
      .finally(() => {
        this.batchIsUsedLoading = false
      })
  }

  public batchIsUsedLoading = false
  // public selectedTitle = this.$createElement('span', '是否补贴')

  public customRowSelectionOptions = {
    getCheckboxProps: (record: any) => {
      return {
        props: {
          disabled: !record.iid, // Column configuration not to be checked
          name: record.name,
        },
      }
    },
  }

  // 当前列表渲染内容
  public renderFields: number = 0 // 0-全部 1-农户 2-耕地

  // 公共字段
  public commonColumns: ITable.IColumn[] = [
    {
      title: '补贴状态',
      dataIndex: 'is_used',
      key: 'is_used',
      width: 100,
      fixed: 'left',
      form: {
        type: 'a-radio-group',
        placeholder: '请选择补贴状态',
        isShowList: false,
        renderMode: ['search'],
        isShowFrom: false,
        isShowQuery: true,
        isExport: true,
        dict: [
          {
            label: '已加入',
            value: '1',
          },
          {
            label: '未加入',
            value: '2',
          },
        ],
      },
    },

    {
      title: '是否加入公示',
      dataIndex: 'is_pub',
      key: 'is_pub',
      width: 140,
      form: {
        type: 'a-radio-group',
        placeholder: '请选择补贴状态',
        isShowList: false,
        isShowQuery: true,
        isShowFrom: false,
        dict: [
          {
            label: '已加入',
            value: '1',
          },
          {
            label: '未加入',
            value: '2',
          },
        ],
      },
    },

    {
      title: '公示编号',
      dataIndex: 'pub_id',
      key: 'pub_id',
      width: 120,
      form: {
        type: 'a-input',
        placeholder: '请输入公示编号',
        isShowList: true,
        isShowFrom: false,
        isShowQuery: true,
        renderFields: [0, 3],
      },
    },

    {
      title: '农户编号',
      dataIndex: 'family_id',
      key: 'family_id',
      width: 160,
      customRender: (value: string, row: IMember, index: number) => {
        if (index === 0) {
          return {
            children: value,
            attrs: {
              colSpan: 2,
            },
          }
        }
        return {
          children: value,
        }
      },
      form: {
        type: 'a-input',
        placeholder: '输入农户编号',
        disabled: ['add', 'edit'],
        isShowFrom: false,
        renderMode: ['search'],
        isShowQuery: true,
      },
    },

    // 表单专用
    {
      title: '农户编号',
      key: 'family_id',
      width: 160,
      form: {
        type: 'a-input',
        placeholder: '--自动生成--',
        disabled: ['add', 'edit'],
        renderMode: ['add', 'edit'],
        isShowQuery: false,
        isShowFrom: true,
        isShowList: false,
      },
    },
    {
      title: '户主姓名',
      dataIndex: 'member_nam',
      key: 'member_nam',
      customRender: (value: string, row: IMember, index: number) => {
        if (index === 0) {
          return {
            children: value,
            attrs: {
              colSpan: 0,
            },
          }
        }
        return {
          children: value,
        }
      },
      width: 80,
      form: {
        type: 'a-input',
        placeholder: '输入户主姓名',
        isShowQuery: true,
        renderMode: ['add', 'edit'],
        validate: '*',
      },
    },
    {
      title: '身份证号',
      dataIndex: 'member_sfz',
      key: 'member_sfz',
      width: 160,
      form: {
        type: 'a-input',
        placeholder: '输入户主身份证号',
        isShowQuery: true,
        renderMode: ['add', 'edit'],
        // validate: '*'
      },
    },
  ]

  // 农户基础信息字段
  get farmerColumns() {
    return [
      {
        title: '户口本编号',
        dataIndex: 'family_book_id',
        key: 'family_book_id',
        width: 100,
        form: {
          type: 'a-input',
          placeholder: '输入户口本编号',
          isShowList: false,
          renderMode: ['add', 'edit'],
        },
      },
      {
        title: '家庭住址',
        // dataIndex: 'member_addr',
        key: 'member_addr',
        align: 'right',
        width: 120,
        scopedSlots: { customRender: 'member_addr' },
        form: {
          type: 'a-textarea',
          placeholder: '输入家庭住址',
          renderMode: ['add', 'edit'],
        },
      },
      {
        title: '人口数',
        dataIndex: 'member_num',
        key: 'member_num',
        width: 60,
      },
      // {
      //   title: '性别',
      //   key: 'member_sex',
      //   width: 50,
      //   scopedSlots: { customRender: 'member_sex' },
      //   form: {
      //     type: 'a-radio-group',
      //     placeholder: '选择性别',
      //     isShowQuery: false,
      //     renderMode: ['add', 'edit'],
      //     defaultValue: 1,
      //     dict: [
      //       {
      //         label: '男',
      //         value: '1'
      //       },
      //       {
      //         label: '女',
      //         value: '2'
      //       }
      //     ]
      //   }
      // },
      {
        title: '手机号',
        dataIndex: 'member_tel',
        key: 'member_tel',
        width: 110,
        form: {
          type: 'a-input',
          placeholder: '输入户主手机号',
          isShowQuery: true,
          renderMode: ['add', 'edit'],
          // validate: '*'
        },
      },
      {
        title: '银行卡号',
       dataIndex: 'member_bank_num',
       key: 'member_bank_num',
       width: 180,
       form: {
         type: 'a-input',
         placeholder: '输入户主银行卡号',
         renderMode: ['add', 'edit'],
         isShowQuery: true,
       },
       },
      {
        title: '开户银行',
        key: 'member_bank_code',
        dataIndex: 'member_bank_code',
        width: 150,
        // scopedSlots: { customRender: 'member_bank_code' },
        form: {
          type: 'a-auto-complete',
          placeholder: '选择/输入 开户银行名称',
          showSearch: true,
          renderMode: ['add', 'edit'],
          dataSource: [],
        },
      },
      {
        title: '备注',
        // dataIndex: 'readme',
        key: 'readme',
        // ellipsis: true,
        scopedSlots: { customRender: 'readme' },
        width: 200,
        form: {
          type: 'a-textarea',
          placeholder: '输入备注',
          isShowQuery: true,
          renderMode: ['add', 'edit'],
        },
      },
    ]
  }

  // 耕地信息字段
  get fieldColumns() {
    return [
      // 搜索专用
      {
        title: '补贴面积（亩）',
        dataIndex: 'field',
        key: 'field',
        align: 'right',
        width: 100,
        form: {
          type: 'a-input',
          placeholder: '请输入耕地面积',
          renderMode: ['farmland', 'edit'],
          isShowQuery: true,
          querySection: true,
          isShowFrom: false,
          isShowList: false,
        },
      },

      // 表单专用
      {
        title: '',
        dataIndex: 'field',
        key: 'field',
        align: 'right',
        width: 100,
        form: {
          type: 'a-input',
          placeholder: '请输入耕地面积',
          renderMode: ['farmland', 'edit', 'add'],
          disabled: true,
          isShowFrom: true,
          slot: 'field',
          colon: false,
          col: 1,
          querySection: true,
          isShowList: false,
        },
      },

      {
        title: '补贴面积（耕地面积或实际耕种面积，亩）',
        key: 'field',
        children: [
          {
            // title: '基础面积依据',
            titleAlias: '基础面积依据',
            slots: { title: 'pay_unit_base_title' },
            scopedSlots: { customRender: 'pay_unit_base' },
            align: 'center',
            width: 150,
            key: 'pay_unit_base',
            form: {
              type: 'a-select',
              placeholder: '请选择基础面积依据',
              isShowFrom: false,
              isExport: false,
              dict: PayUnitType,
            },
          },
          {
            title: '基础面积',
            scopedSlots: { customRender: 'field1' },
            key: 'field1',
            width: 110,
            align: 'right',
            sorter: true,
            sortDirections: ['ascend', 'descend'],
            form: {
              type: 'a-input',
              placeholder: '请输入承包地面积',
              isShowQuery: true,
              querySection: true,
              isShowFrom: false,
              // handler: {
              //   change: (e) => {
              //     console.log(e)
              //     // console.log(arguments)
              //   }
              // },
              renderMode: ['farmland', 'edit'],
            },
          },
          {
            title: '增加面积',
            scopedSlots: { customRender: 'field2' },
            align: 'right',
            key: 'field2',
            width: 110,
            sorter: true,
            sortDirections: ['ascend', 'descend'],
            form: {
              type: 'a-input',
              placeholder: '请输入增加耕地面积',
              isShowQuery: true,
              querySection: true,
              isShowFrom: false,
              renderMode: ['farmland', 'edit'],
            },
          },
          {
            title: '减少面积',
            scopedSlots: { customRender: 'field3' },
            align: 'right',
            key: 'field3',
            width: 110,
            sorter: true,
            sortDirections: ['ascend', 'descend'],
            form: {
              type: 'a-input',
              placeholder: '请输入减少耕地面积',
              isShowQuery: true,
              querySection: true,
              isShowFrom: false,
              renderMode: ['farmland', 'edit'],
            },
          },
          {
            title: '小计',
            dataIndex: 'field',
            key: 'field',
            align: 'right',
            width: 110,
            sorter: true,
            sortDirections: ['ascend', 'descend'],
            form: {
              type: 'a-input',
              placeholder: '请输入耕地总面积',
              renderMode: ['farmland'],
            },
          },
        ],
      },
      // {
      //   title: '粮食种植面积（亩）',
      //   align: 'right',
      //   sorter: true,
      //   sortDirections: ['ascend', 'descend'],
      //   scopedSlots: { customRender: 'plant' },
      //   width: 130,
      //   key: 'plant',
      //   form: {
      //     type: 'a-input',
      //     placeholder: '请输入粮食种植面积',
      //     // addonAfter: "亩",
      //     renderMode: ['search', 'edit', 'add'],
      //     isShowQuery: true,
      //     isShowFrom: true,
      //     col: 1,
      //     isShowList: !this.isDistrictUser,
      //     querySection: true,
      //   },
      // },
      ...([0, 2].includes(this.renderFields) ? this.areaField : []),

      // {
      //   // title: '补贴面积计算依据',
      //   titleAlias: '补贴面积计算依据',
      //   slots: { title: 'pay_unit_title' },
      //   scopedSlots: { customRender: 'pay_unit' },
      //   align: 'center',
      //   width: 150,
      //   key: 'pay_unit',
      //   form: {
      //     type: 'a-select',
      //     placeholder: '请选择补贴参照',
      //     isShowFrom: false,
      //     renderFields: [0],
      //     isShowList: !this.isDistrictUser,
      //     dict: PayUnitType,
      //   },
      // },
      {
        // title: '补贴面积（亩）',
        titleAlias: '补贴面积（亩）',
        slots: { title: 'bt_size_title' },
        sorter: true,
        sortDirections: ['ascend', 'descend'],
        // scopedSlots: { customRender: 'bt_size' },
        key: 'pay_size_total',
        align: 'right',
        dataIndex: 'pay_size_total',
        // sorter: true,
        // sortDirections: ['ascend', 'descend'],
        width: 110,
        form: {
          type: 'a-input',
          isShowFrom: false,
          renderFields: [0],
          isShowList: !this.isDistrictUser,
        },
      },
      {
        // title: '补贴标准(元/亩)',
        titleAlias: '补贴标准(元/亩)',
        slots: { title: 'pay_price_title' },
        dataIndex: 'pay_price',
        key: 'pay_price',
        align: 'right',
        width: 100,
      },
      {
        // title: '补贴总金额（元）',
        titleAlias: '补贴金额（元）',
        slots: { title: 'pay_price_total_title' },
        dataIndex: 'pay_price_total',
        key: 'pay_price_total',
        align: 'right',
        // sorter: true,
        // sortDirections: ['ascend', 'descend'],
        width: 110,
      },
    ]
  }

  // 额外的导出字段
  public exportColumns: ITable.IColumn[] = [
    {
      title: '行政编码',
      dataIndex: 's_a_id',
      key: 's_a_id',
      width: 100,
      form: {
        isShowList: false,
        isShowFrom: false,
        isShowQuery: false,
        isExport: true,
      },
    },
    {
      title: '行政地区',
      dataIndex: 's_a_nam_all',
      key: 's_a_nam_all',
      width: 100,
      form: {
        isShowList: false,
        isShowFrom: false,
        isShowQuery: false,
        isExport: true,
      },
    },
  ]

  // 种植粮食信息
  public grainsColumns: ITable.IColumn[] = []

  get isDistrictUser() {
    return false // this.currentAreaId.length >= 6
  }

  get areaField() {
    return [
      // {
      //   title: '确权面积（亩）',
      //   align: 'right',
      //   sorter: true,
      //   sortDirections: ['ascend', 'descend'],
      //   width: 120,
      //   key: 'field_confirm_t',
      //   // dataIndex: 'field_confirm_t',
      //   scopedSlots: { customRender: 'field_confirm_t' },
      //   form: {
      //     type: 'a-input',
      //     placeholder: '请输入确权面积',
      //     renderMode: ['search', 'edit', 'add'],
      //     isShowQuery: true,
      //     // addonAfter: "亩",
      //     isShowList: !this.isDistrictUser,
      //     isShowFrom: true,
      //     col: 1,
      //     querySection: true,
      //   },
      // },

      // {
      //   title: '二包面积（亩）',
      //   align: 'right',
      //   sorter: true,
      //   sortDirections: ['ascend', 'descend'],
      //   width: 120,
      //   key: 'field_confirm',
      //   // dataIndex: 'field_confirm',
      //   scopedSlots: { customRender: 'field_confirm' },
      //   form: {
      //     type: 'a-input',
      //     placeholder: '请输入二包面积',
      //     renderMode: ['search', 'edit', 'add'],
      //     // tips: '第二轮承包耕地面积',
      //     // addonAfter: "亩",
      //     isShowQuery: true,
      //     isShowFrom: true,
      //     col: 1,
      //     isShowList: !this.isDistrictUser,
      //     querySection: true,
      //   },
      // },

      {
        title: '计税面积（亩）',
        align: 'right',
        sorter: true,
        sortDirections: ['ascend', 'descend'],
        width: 120,
        key: 'field_tax',
        // dataIndex: 'field_tax',
        scopedSlots: { customRender: 'field_tax' },
        form: {
          type: 'a-input',
          placeholder: '请输入农业计税面积',
          renderMode: ['search', 'edit', 'add'],
          isShowQuery: true,
          // addonAfter: "亩",
          isShowFrom: true,
          col: 1,
          isShowList: !this.isDistrictUser,
          querySection: true,
        },
      },
    ]
  }

  get formatColumns() {
    return [
      ...this.commonColumns,
      ...this.exportColumns,
      ...([0, 1].includes(this.renderFields) ? this.farmerColumns : []),
      ...([2].includes(this.renderFields) ? this.areaField : []),
      ...([0, 3].includes(this.renderFields) ? this.fieldColumns : []),

      {
        title: '查询死亡名单',
        dataIndex: 'is_dead',
        key: 'is_dead',
        width: 260,
        form: {
          type: 'a-checkbox-group',
          placeholder: '请选择查重/查错条件',
          dict: [
            {
              label: '已死亡',
              value: '1',
            },
          ],
          renderMode: ['filter'],
          isShowAll: false,
          isShowFrom: false,
          isShowList: false,
          isShowQuery: true,
        },
      },

      {
        title: '选择查重/查错条件',
        dataIndex: 'member_filter',
        key: 'member_filter',
        width: 260,
        form: {
          type: 'a-checkbox-group',
          placeholder: '请选择查重/查错条件',
          dict: [
            {
              label: '姓名为空',
              value: 'member_nam_empty',
            },
            {
              label: '身份证为空',
              value: 'member_sfz_empty',
            },
            {
              label: '联系电话为空',
              value: 'member_tel_empty',
            },
            {
              label: '身份证查重',
              value: 'member_sfz_repeat',
            },
            // {
            //   label: '银行卡号查重',
            //   value: 'member_bank_num_repeat',
            // },
            // {
            //   label: '户主查重',
            //   value: 'family_id_repeat',
            // },
            {
              label: '姓名查重',
              value: 'member_nam_repeat',
            },
          ],
          mode: 'multiple',
          renderMode: ['filter'],
          isShowAll: false,
          isShowFrom: false,
          isShowList: false,
          isShowQuery: true,
        },
      },

      {
        title: '信息异常原因',
        key: 'error_msg',
        dataIndex: 'error_msg',
        width: 210,
        form: {
          isShowQuery: false,
          isShowFrom: false,
          renderFields: [0, 3],
        },
      },

      // 筛选专用
      {
        title: '操作',
        key: 'action',
        width: 160,
        fixed: 'right',
        scopedSlots: { customRender: 'action' },
      },
    ]
  }

  get formFieldColumns() {
    return this.formColumns.slice(9)
  }

  public formItemLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 16 },
  }

  // 产品列表表格信息
  // @ts-ignore
  public columns: ITable.IColumn[] = this.formatColumns

  public tableApi = {
    list: famerServices.getMemberList,
    add: famerServices.updateMember,
    edit: famerServices.updateMember,
    del: famerServices.deleteMember,
    exportExecl: famerServices.exportExecl,
    import: famerServices.exportExecl,
    // imageUpload: 'uploadStoreImage',
    // imageRemove: 'delStoreImage'
  }

  @Watch('renderFields')
  public handlerChangeRenderFields() {
    // @ts-ignore
    this.columns = this.formatColumns.filter((column) => {
      // @ts-ignore
      if (!column.form?.renderFields) return true
      // @ts-ignore
      return column.form?.renderFields.includes(this.renderFields)
    })
    if (![0, 3].includes(this.renderFields)) {
      // @ts-ignore
      this.customRowSelectionOptions = false
    } else {
      // @ts-ignore
      this.customRowSelectionOptions = null
    }
    this.handlerAddGrainColumn()
  }

  @Watch('currentAreaId', { immediate: true })
  public handlerCurrentAreaIdChange() {
    this.commonParams.s_a_id = this.currentAreaId
    this.handlerChangeRenderFields()
    this.isInitSelected = false
    this.getData()
  }

  public mounted() {
    // @ts-ignore
    // @todo 复选框权限控制
    // this.rowSelection.getCheckboxProps = (record) => {
    //   return {
    //     disabled: true
    //   }
    // }
    this.handlerAddGrainColumn()
  }

  public handlerAddGrainColumn() {
    const grains = [
      '水稻',
      '玉米',
      '小麦',
      '红苕',
      '马铃薯',
      '大豆',
      '绿豆',
      '豌葫豆',
      '高粱',
      '荞麦',
      '肾豆',
      '红小豆',
    ]
    const grainsColumns = grains.map((item, index) => {
      const key = 'plant' + (index + 1)
      return {
        title: item,
        dataIndex: key,
        key,
        form: {
          type: 'a-input',
          placeholder: `请输入${item}面积`,
          renderMode: ['grain'],
          isShowList: false,
        },
      }
    })
    // @ts-ignore
    this.columns = this.columns.concat(grainsColumns)
  }

  public async handlerTableAdd() {
    await publicServices.checkAreaLock({
      s_a_id: this.currentAreaId,
    })
    this.tableAdd()
    this.$nextTick(() => {
      this.currentRow = Object.assign(
        {},
        {
          s_a_id: this.currentAreaId,
          member_sex: '1',
          member_addr: this.currentAreaName,
        }
      )
      this.customMode = 'add'
      this.visibleTitle = '添加农户'
    })
  }

  public handlerUploadProcess(type: string, title: string) {
    this.$dialog(
      UploadProcess,
      {
        currentAreaId: this.currentAreaId,
        type,
      },
      {
        title: '查询' + title + '上传进度',
        width: 1000,
      }
    )
  }

  public handlerFamily(row: IMember) {
    this.$dialog(
      Family,
      {
        currentMember: row,
      },
      {
        title: '管理家庭成员',
        width: '80%',
        centered: true,
        footer: null,
      }
    )
    this.events.trigger('select-houseHolder', row)
  }

  public handleFormSubmit() {
    this.handleSubmit({}, true, (result) => {
      // if (result.pub_id) {
      //   return new Promise((resolve, reject) => {
      //     this.$confirm({
      //       content: '当前农户信息已公示，修改数据后需要重新公示，请确认！',
      //       centered: true,
      //       onOk: () => {
      //         resolve(result)
      //       },
      //       onCancel: () => {
      //         reject()
      //       },
      //     })
      //   })
      // }
      return result
    })
  }

  // 编辑农户基础数据
  public async handleTableEdit(row: any, mode: string = 'edit') {
    this.customMode = mode
    this.tableApi.edit = famerServices.updateMember
    this.tableEdit(Object.assign({}, row))
    this.visibleTitle = '修改农户耕保信息'
  }

  public handlerSiftDead() {
    this.$dialog(
      Result,
      {
        currentAreaId: this.currentAreaId,
      },
      {
        title: '筛查当前行政区下死亡农户列表',
        width: 800,
        okText: '下载名单',
        on: {
          ok: async () => {
            await this.exportExecl(
              ['member_nam', 'member_sfz', 's_a_nam_all', 'is_used'],
              {
                exportExeclMode: '1',
              }
            )
            // await famerServices.exportExecl({
            //   s_a_id: this.currentAreaId,
            //   switch: 2,
            //   exportExeclMode: 1,
            //   keys: [
            //     'member_nam',
            //     'member_sfz',
            //     's_a_nam_all',
            //     'is_used'
            //   ]
            // })
          },
        },
      }
    )
  }

  get totalPlant() {
    if (typeof this.currentRow.plant1 === 'undefined') return 0
    let count = 0
    Object.keys(this.currentRow)
      .filter((_) => /^plant(.+)/.test(_))
      .forEach((key) => {
        count += +this.currentRow[key] || 0
      })
    return count.toFixed(3)
  }

  @Watch('totalPlant')
  public handlerChangeCurrent() {
    this.visibleTitle =
      // @ts-ignore
      this.currentRow.member_nam +
      ' 粮食种植面积（亩），当前总计' +
      this.totalPlant +
      '亩'
  }

  // 编辑种粮数据
  public async handlePlantEdit(row: IGrain, mode: string) {
    this.customMode = mode
    this.tableApi.edit = famerServices.updateMemberPlant
    famerServices
      .getMemberPlant({
        family_id: row.family_id,
        s_a_id: row.s_a_id,
      })
      .then((res) => {
        this.tableEdit(
          Object.assign(
            {},
            row,
            res.data || {
              plant1: 0,
              plant2: 0,
              plant3: 0,
              plant4: 0,
              plant5: 0,
              plant6: 0,
              plant7: 0,
              plant8: 0,
              plant9: 0,
              plant10: 0,
              plant11: 0,
              plant12: 0,
            }
          )
        )
        if (mode === 'grain') {
          this.$nextTick(() => {
            this.visibleTitle =
              // @ts-ignore
              row.member_nam +
              ' 粮食种植面积（亩），当前总计' +
              this.totalPlant +
              '亩'
          })
        }
      })
  }

  public drawerVisible = false
  public currentFieldType = 1
  // 管理耕地信息
  public handlerManageFarmLand(row: IGrain, mode: number) {
    this.currentRow = Object.assign({}, row)
    this.currentFieldType = mode
    this.drawerVisible = true
  }

  // 管理耕地信息
  public handlerAreaManage(row: IGrain, mode: string) {
    const titleMap: Record<string, string> = {
      field_confirm_t: '确权面积明细',
      field_confirm: '二包面积明细',
      field_tax: '计税面积明细',
    }

    this.$dialog(
      AreaManage,
      {
        record: {},
        currentType: mode,
        currentField: row,
        // currentAreaId: this.currentField.s_a_id,
        // currentMemberId: this.currentField.family_id,
        // currentAreaName: this.currentField.s_a_nam,
        on: {
          ok() {},
          cancel() {
            console.log('cancel 回调')
          },
          close() {
            console.log('modal close 回调')
          },
        },
      },
      // modal props
      {
        title: titleMap[mode],
        width: '80%',
        maskClosable: false,
        footer: null,
      }
    )
  }

  get isShowPayUnitSet() {
    return (
      this.currentAreaId.length === 6 &&
      userModule.currentUserArea.s_a_id.length <= 6
    )
  }

  get isThanArea() {
    return userModule.isThanArea
  }

  public handlerUpdateSubsidy(type: string) {
    const s_a_id = this.currentAreaId
    const _self = this
    const _default =
      type === 'uint_base'
        ? this.tableData[1]?.pay_unit_base
        : this.tableData[1]?.pay_unit
    this.$dialog(
      UpdateSubsidy,
      {
        currentPayUnitId: _default,
        type,
      },
      {
        title: '变更' + (type === 'unit' ? '补贴核算依据' : '基础面积依据'),
        on: {
          async ok() {
            try {
              await subsidyServices.updateSubsidyStandard({
                // @ts-ignore
                [type === 'unit' ? 'pay_unit' : 'pay_unit_base']:
                  // @ts-ignore
                  this.$refs._component.current,
                s_a_id,
              })
              _self.getData()
              return true
            } catch (err) {
              return false
            }
          },
        },
      }
    )
  }

  public handlerFarmLandCancel() {
    this.drawerVisible = false
    this.getData()
  }
}
</script>

<style scoped lang="less">
@import './MemberList.less';
.action-button {
  margin: 0px 10px 0px 10px;
}
.form-item-class {
  margin-bottom: 0px;
}
.img-box {
  width: 100px;
  height: 100px;
  margin: 10px;
}
.item-blue {
  color: #1989fa;
}

/deep/ .ant-table {
  thead tr {
    background: #fafafa;
  }

  tbody tr {
    background: #fff;
  }

  th[key='member_nam'],
  tr:not(:nth-child(1)) td:nth-of-type(5) {
    position: sticky;
    left: 60px;
    top: 0;
    z-index: 99;
    background: inherit;
  }
}

/deep/ .ant-table-thead th {
  // text-align: center!important;
}

/deep/ .ant-card-head-title {
  padding-top: 0px !important;
}

.opreate {
  margin-left: 6px;
  margin-right: 10px;
  display: inline-block;
}
.page-title {
  display: flex;
  align-items: center;
}

/deep/ th[key='selection-column'] {
  position: relative;
  padding-top: 24px !important;
  padding-bottom: 0 !important;
  &::after {
    content: '补贴';
    position: absolute;
    top: 10px;
    left: 50%;
    width: 100%;
    transform: translateX(-50%);
  }
}

.message-tips {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

/deep/ .has-error {
  background-color: rgba(255, 173, 50, 0.1);
}
.one-line {
  height: 42px;
  overflow: hidden;
}

/deep/ .search-form {
  .form_item_is_used,
  .form_item_is_pub,
  .form_item_member_filter,
  .form_item_is_dead {
    .ant-form-item-label {
      font-weight: bold;
    }
  }
}

/deep/ .form_item_field {
  // border-top: 1px solid #ddd;
  // padding-top: 10px;
}

.custom-field {
  text-align: center;
  margin-bottom: 36px;
  input {
    text-align: center;
  }
}
.field-count {
  margin-bottom: 36px;
  border-bottom: 1px solid #aaa;
}
.edit-container {
  display: flex;
  form {
    flex: 1;
    min-width: 400px;
  }
}

.field-select {
  margin-top: 15px;
}

/deep/ .table-layout-header {
  padding-bottom: 0 !important;
}

/deep/ .ant-tabs-bar {
  border-bottom: 1px solid #aaa;
  margin-bottom: 4px;
}
/deep/ .ant-tabs.ant-tabs-card .ant-tabs-card-bar {
  .ant-tabs-tab {
    border: 1px solid #aaa;
  }
  .ant-tabs-tab-active {
    border-bottom: 1px solid #fff;
  }
}
/deep/ .edit-container .form_item_field > div {
  width: 100%;
}
</style>
